<?php


namespace App\Http\Controllers\User\userCenter;


use App\Http\Controllers\Controller;
use App\Services\MemberService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 积分商城
 * Class ShopController
 * @package App\Http\Controllers\User\userCenter
 */
class ShopController extends Controller
{
    /**
     * 获取商品列表
     */
    public function getGoods()
    {
        $list = DB::table('shop_goods')
            ->where('store', '>', 0)
            ->orderBy('sort', 'desc')
            ->get();
        return successResp($list);
    }

    /**
     * 获取地址列表
     */
    public function getAddress(Request $request)
    {
        $user = $request->userInfo;
        $list = DB::table('shop_member_address')
            ->where('member_id', $user->id)
            ->orderBy('is_default', 'asc')
            ->get();
        return successResp($list);
    }

    /**
     * 保存地址
     */
    public function saveAddress(Request $request)
    {
        //验证表单
        $this->validate($request, [
            'id' => ['int'],
            'nickname' => ['required','string'],
            'mobile' => ['required','string'],
            'address' => ['required','string'],
            'is_default' => ['required','int'],
        ]);
        $user = $request->userInfo;
        $data = [
            'nickname' => $request->nickname,
            'mobile' => $request->mobile,
            'address' => $request->address,
            'is_default' => $request->is_default,
            'member_id' => $user->id,
            'union_id' => $user->unionid
        ];
        if ($request->id) {
            // 更新
            $address = $list = DB::table('shop_member_address')->find($request->id);
            if (!$address || $address->member_id != $user->id) {
                return errorResp('未查询到地址');
            }
            DB::table('shop_member_address')->where('id', $address->id)->update($data);
            return successResp('');
        }
        DB::table('shop_member_address')->insert($data);
        return successResp('');
    }

    /**
     * 删除地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function delAddress(Request $request)
    {
        //验证表单
        $this->validate($request, [
            'id' => ['int', 'required'],
        ]);
        $user = $request->userInfo;
        $address = DB::table('shop_member_address')->find($request->id);
        if (!$address || $address->member_id != $user->id) {
            return errorResp('未查询到地址');
        }
        DB::table('shop_member_address')->where('id', $request->id)->delete();
        return successResp('');
    }

    /**
     * 订单列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function orderList(Request $request)
    {
        $user = $request->userInfo;
        $list = DB::table('shop_order')
            ->where('member_id', $user->id)
            ->orderBy('id', 'desc')
            ->get();
        return successResp($list);
    }

    /**
     * 下单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function createOrder(Request $request)
    {
        $this->validate($request, [
            'goods_id' => ['int', 'required'],
            'address_id' => ['int', 'required'],
        ]);
        $userInfo = $request->userInfo;
        $goods = DB::table('shop_goods')->find($request->goods_id);
        if (!$goods) {
            return errorResp('未查询到商品');
        }
        if ($goods->store <= 0) {
            return errorResp('库存不足');
        }
        $address = DB::table('shop_member_address')->find($request->address_id);
        if (!$address) {
            return errorResp('地址错误');
        }
        if ($address->member_id != $userInfo->id) {
            return errorResp('地址错误');
        }
        if ($userInfo->integral < $goods->integral) {
            return errorResp('积分不足');
        }
        DB::beginTransaction();
        try {
            // 生成订单
            $orderInfo = [
                'member_id' => $userInfo->id,
                'union_id' => $userInfo->unionid,
                'goods_id' => $request->goods_id,
                'goods_title' => $goods->title,
                'image' => $goods->image,
                'integral' => $goods->integral,
                'address_id' => $request->address_id,
                'status' => 1,
                'post_no' => ''
            ];
            $orderInfo = DB::table('shop_order')->insertGetId($orderInfo);
            if (!$orderInfo) {
                throw new \Exception('创建订单失败');
            }
            // 扣减库存
            if (!DB::table('shop_goods')->where('id',$request->goods_id)->decrement('store', 1)) {
                throw new \Exception('扣减库存失败');
            }
            // 修改用户余额
            MemberService::setMemberBalance(
                $userInfo,
                MemberService::BalanceTypeJf,
                MemberService::FromTypeDhGoods,
                $orderInfo,
                -$goods->integral,
                "商城兑换【{$goods->title}】"
            );
            Db::commit();
            return successResp($orderInfo);
        }catch (\Exception $e) {
            Db::rollback();
            return errorResp($e->getMessage());
        }
    }

    /**
     * 积分列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function integralList(Request $request)
    {
        $user = $request->userInfo;
        $list = DB::table('user_balance_log')
            ->where('unionid', $user->unionid)
            ->where('balance_type', MemberService::BalanceTypeJf)
            ->orderBy('id', 'desc')
            ->limit(20)
            ->get();
        foreach ($list as $v) {
            $v->create_time = date('Y-m-d H:i:s', $v->create_time);
        }
        return successResp($list);
    }
}
